import { history } from 'umi';
import { extend } from "umi-request";
import { notification } from 'antd';
import { STATIC } from '../services/config';

const request = extend();

const REQUEST_LIST = []; // 请求栈
let IS_OVERDUE = false; // 是否过期
const loginOverdue = STATIC.message.loginOverdue;
const requestError = STATIC.message.requestError;
const customRequest = function (reqParams = {}) {
  if (IS_OVERDUE) return; // 如果是过期状态不再发送请求
  if (isRepeatRequest(reqParams)) return; // 防重复请求 在前一次请求没有返回时不能进行重复操作
  const method = reqParams.method || 'get';
  const params = reqParams.params || {};
  const obj = { method };
  params.current ? params.pageNo = params.current : null;  // 分页接口处理 与组件保持一致
  method === 'post' ? obj.data = params : obj.params = params;
  return new Promise(function (resolve, reject) {
    request(reqParams.api, obj).then(function (res) {
      const code = res.code;
      switch (code) {
        case '200': // 正确
          ('totalSize' in res) ? resolve(res) : resolve(res.data) // 是否为分页
          break
        // case '401': // 登录过期
        //   IS_OVERDUE = true;
        //   notification.error({ message: '过期', description: res.error || loginOverdue })
        //   reject({ code, error: res.error || loginOverdue })
        //   setTimeout(function () {
        //     IS_OVERDUE = false;
        //     history.replace('/user/login');
        //     // window.location.reload();
        //   }, 1000)
        //   break
        default:
          reject({ code, message: res.error || requestError });
          notification.error({ message: '提示！', description: res.error });
          break
      }
    }).catch(function (err) {
      const { status, message } = err.data;
      switch (status) {
        case 401:
          IS_OVERDUE = true;
          notification.error({ message: '提示！', description: message || '请求过期！请刷新页面' });
          setTimeout(function () {
            IS_OVERDUE = false;
            history.replace('/user/login');
          }, 1000)
          break
        default:
          notification.error({ message: '提示！', description: message || '请求超时！请刷新页面' });
          break
      }
    }).finally(function () {
      deleteRequest(reqParams)
    })
  })
}

/* 
* 判断是否为重复请求
* 依据请求栈中还存在未完成的请求 判断当前请求是否为重复请求
* 通过比对请求的api来返回
*/
const isRepeatRequest = (reqParams) => {
  const { api } = reqParams;
  const findInx = REQUEST_LIST.findIndex(function (item) {
    return item.api === api;
  })
  if (findInx === -1) {
    REQUEST_LIST.push(reqParams);
    return false
  }
  return true
}

/* 
* 请求完成后 从请求栈中剔除
*/
const deleteRequest = (reqParams) => {
  const { api } = reqParams;
  const findInx = REQUEST_LIST.findIndex(function (item) {
    return item.api === api;
  })
  findInx >= 0 ? REQUEST_LIST.splice(findInx, 1) : null
}

export default customRequest